import { EditContext, IEditor } from '@visactor/vtable-editors';

const input = document.createElement( 'input' );
// 设置输入框的属性
input.type = 'number';
input.id = 'positiveInteger';
input.name = 'positiveInteger';
input.min = '1';
input.step = '1';
input.style.padding = '4px';
input.style.boxSizing = 'border-box';
input.style.position = 'absolute';

// 监听输入事件，屏蔽非法输入
input.addEventListener( 'input', function(){
  // 获取当前输入值
  let currentValue = input.value;
  
  // 检查输入值是否为正整数
  if( !/^\d+$/.test( currentValue ) ){
    // 如果不是正整数，恢复到上一个合法值
    input.value = input.dataset.lastValidValue || '1';
  }
  else{
    // 如果是正整数，保存到dataset中，以便更新数据时进行校验
    input.dataset.lastValidValue = currentValue;
  }
} );


// @arco-design/web-vue的数字输入组件
export class NumberEditor implements IEditor{
  value: number = 20;
  element!: HTMLInputElement;
  container!: HTMLElement;
  successCallback?: Function;
  
  onStart( {
    container,
    value,
    referencePosition
  }: EditContext )
  {
    this.container = container;
    input.value = value;
    const {
            top,
            left,
            width,
            height
          } = referencePosition.rect;
    input.style.top = top + 'px';
    input.style.left = left + 'px';
    input.style.width = width + 'px';
    input.style.height = height + 'px';
    
    container.appendChild( input );
    this.element = input;
  }
  
  getValue(){
    return this.element.value;
  }
  
  onEnd(){
    this.container.removeChild( this.element );
  }
  
  isEditorElement( target: HTMLElement ){
    return target === this.element;
  }
}
